#include "ipc.h"
#include "timer.h"
#include "mysql.h"

static uv_loop_t* loop;
static uv_signal_t sigint_handler;
static uv_signal_t sigterm_handler;

int global_init();
void global_uninit();

void signal_handler(uv_signal_t* handle, int signum) {
    printf("Received exit signal \n");
    global_uninit();
    uv_stop(loop);
}

int global_init() {
    int ret = 0;

    // 数据库初始化
    init_db();

    // IPC初始化
    if (init_ipc() != 0) {
        ret = -1;
    }

    // 定时器初始化
    loop = uv_default_loop();
    if (init_timer(loop) != 0) {
        ret = -1;
    }

    // 注册退出信号
    uv_signal_init(loop, &sigint_handler);
    uv_signal_start(&sigint_handler, signal_handler, SIGINT);
    uv_signal_init(loop, &sigterm_handler);
    uv_signal_start(&sigterm_handler, signal_handler, SIGTERM);

    return ret;
}

// 业务逻辑相关反初始化
void global_uninit() {
    uninit_timer();
    uninit_ipc();
    uninit_db();
    uv_signal_stop(&sigint_handler);
    uv_signal_stop(&sigterm_handler);
}

int main(int argc, char *argv[]) {
    // 初始化
    if (global_init() < 0) {
        goto error;
    }

    // 进入事件机制
    uv_run(loop, UV_RUN_DEFAULT);

error:
    global_uninit();
    return 0;
}